<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/16
 * Time: 10:33
 */

namespace app\portal\controller;
use cmf\controller\HomeBaseController;
use app\portal\model\PortalCategoryModel;
use app\portal\service\PostService;
use app\portal\model\PortalPostModel;
use think\Db;


class ForumController extends HomeBaseController
{
    //论坛首页
    public function index(){
        $model = new PortalCategoryModel();
        $category=$model->where('parent_id',6)->column('id,name');
        $category[6]='志愿服务心得';
//        dump($category);
        $category_id=input('cate');
        if($category_id){
            $category_list=$category_id;
            $this->assign('cate_id',$category_id);
        }else{
            $category_list='';
            foreach ($category as $k=>$v){
                $category_list.=$k.',';
            }
            //$category_list='6,7,8,';
            $this->assign('cate_id','');
        }
        $this->assign('category',$category);
        $this->assign('category_list',$category_list);
        return $this->fetch(':forum');
    }
    //添加文章
    public function article_add()
    {
        $userId = cmf_get_current_user_id();
        if (empty($userId)) {
            if ($this->request->isAjax()) {
                $this->error("您尚未登录", url("/"));
            } else {
                $this->error("您尚未登录","portal/index/register");
            }
        }
        $model = new PortalCategoryModel();
        $category=$model->where('parent_id',6)->column('id,name');
        $category[6]='志愿者论坛';
        $this->assign('category',$category);
        return $this->fetch(':newArticle');
    }

    //保存文章
    public function addPost()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();


            //状态只能设置默认值。未发布、未置顶、未推荐
            $data['post']['post_status'] = 0;
            $data['post']['is_top'] = 0;
            $data['post']['recommended'] = 0;


            $post = $data['post'];

            $result = $this->validate($post, 'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }

            $portalPostModel = new PortalPostModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }
            $data['post']['user_id'] = cmf_get_current_user_id();

            $portalPostModel->adminAddArticle($data['post'], $data['post']['categories']);

            $data['post']['id'] = $portalPostModel->id;
            //发表即发布
//            Db::name('portal_post')->where('id', $data['post']['id'])->update(['published_time'=>time()]);
            $hookParam = [
                'is_add' => true,
                'article' => $data['post']
            ];
            hook('portal_admin_after_save_article', $hookParam);


            $this->success('添加成功!', url('/forum'));
        }
    }
    //文章详情
    public function detail(){
//        return $this->fetch(':forumDetail');
//exit;
        $portalCategoryModel = new PortalCategoryModel();
        $postService         = new PostService();

        $articleId  = $this->request->param('id', 0, 'intval');
        $categoryId = $this->request->param('cid', 0, 'intval');
        $article    = $postService->publishedArticle($articleId, $categoryId);

        if (empty($article)) {
            abort(404, '文章不存在!');
        }


        $prevArticle = $postService->publishedPrevArticle($articleId, $categoryId);
        $nextArticle = $postService->publishedNextArticle($articleId, $categoryId);

        $tplName = 'forumDetail';

        if (empty($categoryId)) {
            $categories = $article['categories'];

            if (count($categories) > 0) {
                $this->assign('category', $categories[0]);
            } else {
                abort(404, '文章未指定分类!');
            }

        } else {
            $category = $portalCategoryModel->where('id', $categoryId)->where('status', 1)->find();

            if (empty($category)) {
                abort(404, '文章不存在!');
            }

            $this->assign('category', $category);

            $tplName = empty($category["one_tpl"]) ? $tplName : $category["one_tpl"];
        }

        Db::name('portal_post')->where('id', $articleId)->setInc('post_hits');


        hook('portal_before_assign_article', $article);

        $this->assign('article', $article);
        $this->assign('prev_article', $prevArticle);
        $this->assign('next_article', $nextArticle);

        $tplName = empty($article['more']['template']) ? $tplName : $article['more']['template'];

        return $this->fetch("/$tplName");
    }

}